package com.gulimall.cart.controller;

import com.common.constant.auth.AuthConstant;
import com.common.to.cart.UserInfoTO;
import com.common.vo.cart.CartItemVO;
import com.common.vo.cart.CartVO;
import com.gulimall.cart.interceptor.CartInterceptor;
import com.gulimall.cart.service.impl.CartServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @Author: Ren(任佳宝)
 * @Description: CartController
 * @Date: 2025/2/10 上午10:19
 * @Version: 1.0
 */

@Controller
public class CartController {

    @Autowired
    CartServiceImpl cartService;

    @GetMapping("/cart.html")
    public String cartListPage(Model model) {

      /*
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        System.out.println(userInfoTO);
      */

        CartVO cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    @GetMapping("/addCartItem")
    public String addToCart(RedirectAttributes attributes, @RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {

        cartService.addToCart(skuId, num);
        attributes.addAttribute("skuId", skuId); // 会自动在URL后边拼接 参数
        // 请求重定向给addToCartSuccessPage.html，防刷
        return "redirect:http://cart.gulimall.com/addToCartSuccessPage.html";
    }

    /**
     * 商品添加购物车成功页（防刷）
     */
    @GetMapping(value = "/addToCartSuccessPage.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model) {
        // 重定向到成功页面。再次查询购物车数据即可
        CartItemVO cartItemVo = cartService.getCartItem(skuId);
        model.addAttribute("cartItem", cartItemVo);
        return "success";
    }

    /**
     * 更改购物车商品选中状态
     */
    @GetMapping(value = "/checkItem")
    public String checkItem(@RequestParam(value = "skuId") Long skuId,
                            @RequestParam(value = "checked") Integer check) {
        cartService.checkItem(skuId, check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 改变商品数量
     */
    @GetMapping(value = "/countItem")
    public String countItem(@RequestParam(value = "skuId") Long skuId,
                            @RequestParam(value = "num") Integer num) {
        cartService.changeItemCount(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 删除商品信息
     */
    @GetMapping(value = "/deleteItem")
    public String deleteItem(@RequestParam("skuId") Integer skuId) {
        cartService.deleteIdCartInfo(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

}
